﻿using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using Microsoft.Extensions.Options;
using Xc.DataAccess.Core;
using Xc.WaterMeters.ServerHosts.Models;
using Xc.WaterMeters.ServerHosts.Services;

namespace Xc.WaterMeters.ServerHosts.Controllers
{
    /// <summary>
    /// 通知管理服务
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class NotifyController : ControllerBase
    {
        private readonly IModifyAppSettingService modifyAppSettingService;
        private readonly IOptions<AppSettings>  _appSettings;
        /// <summary>
        /// 通知管理服务
        /// </summary>
        /// <param name="appSettings"></param>
        public NotifyController(IOptions<AppSettings> appSettings, IModifyAppSettingService modifyAppSettingService)
        {
            _appSettings = appSettings;
            this.modifyAppSettingService = modifyAppSettingService;
        }
        /// <summary>
        /// 获取所有的通知列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public Dictionary<string, string[]> GetNotifyLists()
        {
            return   _appSettings.Value.Notifys;
        }
        /// <summary>
        /// 获取服务器列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]

        public SortedSet<string> GetServers()
        {
            return _appSettings.Value.NotifyPath;
        }
        /// <summary>
        /// 添加服务器
        /// </summary>
        /// <param name="serverPathBase"></param>
        /// <returns></returns>
        [HttpGet]
        public Result AddServer(string serverPathBase)
        {
           var res=  _appSettings.Value.NotifyPath.Add(serverPathBase);
            _appSettings.Value.Regenerate();
            modifyAppSettingService.UpdateSettingFile(_appSettings.Value);
            if (res==false)
            {
                return Result.Reject("服务器已存在，不可重复添加");
            }
            else
            {
                return Result.Accept("服务器添加成功");
            }
        }
        /// <summary>
        /// 删除服务器
        /// </summary>
        /// <param name="serverPathBase"></param>
        /// <returns></returns>
        [HttpGet]
        public Result RemoveServer(string serverPathBase)
        {
            var res = _appSettings.Value.NotifyPath.Remove(serverPathBase);
            _appSettings.Value.Regenerate();
            modifyAppSettingService.UpdateSettingFile(_appSettings.Value);
            if (res == false)
            {
                return Result.Reject("服务器不存在");
            }
            else
            {
                return Result.Accept("服务器删除成功");
            }
        }
    }
}
